<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
            <legend>热更新分组{{detail.id?'编辑':'添加'}}</legend>
        </fieldset>
        <form class="layui-form" action="javascript:;" lay-filter="formOne">

            <div class="layui-form-item">
                <label class="layui-form-label">选择渠道</label>
                <div class="layui-input-block">
                    <input type="checkbox" class="layui-input" v-for="item in channels" :title="item.name" lay-filter="channel"
                           name="channelId[]" :value="item.id" :checked="channelIsChecked(item.id)" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择包</label>
                <div class="layui-input-block" id="temp-package-box">

                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">签到奖励描述内容</label>
                <div class="layui-input-block">
                    <input type="text" name="qddescription" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input" >
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">签到奖励开关</label>
                <div class="layui-input-block">
                    <input type="radio" name="isSign" lay-verify="required" class="layui-input" title="是"
                           :checked="(formData.isSign==1) ? true : false" value="1">
                    <input type="radio" name="isSign" lay-verify="required"  class="layui-input" title="否" value="0">
                </div>
                <div class="layui-form-mid">
                    游戏前端是否显示签到模块
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">绑定账号开关</label>
                <div class="layui-input-block">
                    <input type="radio" name="bind" lay-verify="required" class="layui-input" title="是"
                           :checked="(formData.bind==1) ? true : false" value="1">
                    <input type="radio" name="bind" lay-verify="required"  class="layui-input" title="否" value="0">
                </div>
                <div class="layui-form-mid">
                    游戏前端是否显示绑定模块
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">PC端充值开关</label>
                <div class="layui-input-block">
                    <input type="radio" name="isPay" lay-verify="required" class="layui-input" title="是"
                           :checked="(formData.isPay==1) ? true : false" value="1">
                    <input type="radio" name="isPay" lay-verify="required"  class="layui-input" title="否" value="0">
                </div>
                <div class="layui-form-mid">
                    游戏PC前端是否能充值
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">公众号二维码链接</label>
                <div class="layui-input-block">
                    <input type="text" name="qdweixinbg" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">公众号名称</label>
                <div class="layui-input-block">
                    <input type="text" name="qdweixin" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" >
                <label class="layui-form-label">奖品列表</label>
                <button type="button"  class="layui-btn layui-btn-sm layui-btn-normal" v-on:click="listShowAdd()"><i class="fa fa-plus"></i>添加</button>
                <div class="layui-input-block">
                    <ul id="server-show">
                        <li class="layui-clear" v-for="(item,index) in rewardlist">
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input " v-model="item.id" />
                            </div>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input " v-model="item.num" />
                            </div>
                            <div class="layui-input-inline">
                                <i class="fa fa-trash icon cursor del" v-on:click="rewardlist.splice(index,1)"></i>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
</div>
<style>

    #server-show li:nth-child(1){margin-top: 0;}
    #server-show li{
        margin-top:5px;
    }
    #server-show li .fa-trash{
        color:red;
    }
</style>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/js/common.js?v=5" charset="utf-8"></script>
<script id="tempCheckboxList" type="text/html">
    {{# layui.each(d.tempPackages,function(index,item){ }}
    <input type="checkbox" class="layui-input" title="{{item.package_no}}" name="packageId[]"
           value="{{item.id}}" {{ d.checkedIds.indexOf(item.id)!==-1 ? 'checked':'' }} />
    {{# })  }}
</script>
<script>
    from = null;
    Id = urlParam('id')
    initChannels = []; //编辑的时候初始化的渠道数组
    new Vue({
        el:"#app",
        data:{
            rewardlist:[],
            channels:[], //显示的候选渠道
            packages:[], //所有的包
            tempPackages:[],//临时选择的包
            fromPackagesno:[],//选中的包
            packageCheckedIds:[],
            qddescription:null,
            isSign:null,
            isPay:null,
            bind:null,
            qdweixinbg:null,
            qdweixin:null,
            detail:{
                id:null,
                name:null,
                channels:[],
                packages:[],

            },
            formData:{
                show:null,
                status:null,
                busy_status:null,
                pay_status:null,
                white_status:"0",
            },
        },
        methods:{
            listShowAdd:function(){
                this.rewardlist.push({id:"",num:""})
            },

            getValuesFromForm:function(keyStr){
                var obj = form.val('formOne');
                console.log('查看总信息'+obj)
                var values = [];
                for(var key in obj) {
                    var val = obj[key];
                    console.log('查看遍历信息'+obj[key])
                    if (key.indexOf(keyStr)!==-1){
                        values.push(parseInt(val))
                    }
                }
                return values;
            },
            channelIsChecked:function (id) {
                var _this = this;
                var checked = false;

                _this.detail.channels.forEach(x=>{
                    if (x.id === id) {
                        checked = true;
                    }
                })
                return checked;
            }
        },
        updated:function(){
            form.render();
        },
        mounted:function(){
            var _this = this;
            layui.use(['form','jquery','laytpl'], function () {
                form = layui.form;
                var layer = layui.layer ,$ = layui.jquery,laytpl = layui.laytpl;

                //渠道列表
                $.get("/admin/gameChannel/paginate",{page:1,limit:9999},function(res){
                    _this.channels = res.data;
                });
                //包列表
                $.get("/admin/gamePackage/paginate",{page:1,limit:9999},function(res){
                    _this.packages = res.data;
                    if (Id){
                        $.get('/admin/gameSign/'+Id,{},function(res){
                            console.log('channels'+res.data.channels);
                            console.log('Id:'+Id);
                            // 使用 layui 的表单赋值方法
                            layui.form.val("formOne", {
                                "qddescription": res.data.qddescription.toString(),
                                "isSign": res.data.isSign.toString(),
                                "bind": res.data.bind.toString(),
                                "isPay": res.data.isPay,
                                "qdweixinbg": res.data.qdweixinbg.toString(),
                                "qdweixin": res.data.qdweixin.toString(),
                            });
                            _this.detail = res.data;
                            var channels = res.data.channels;
                            var packages = res.data.packages;
                            initChannels =channels;
                            var rewardlistData = JSON.parse(res.data.rewardlist);
                            _this.rewardlist = rewardlistData;

                            var channelIds = []
                            channels.forEach(x=>{
                                console.log('x.id'+x.id);
                                channelIds.push(x.id)
                            })

                            showPackagesByChannelIds(channelIds)
                            var packageCheckedIds = [];
                            packages.forEach(x=>{
                                packageCheckedIds.push(x.id)
                            })
                            _this.packageCheckedIds = packageCheckedIds;
                        });
                    }
                });
                function showPackagesByChannelIds(channelIds) {
                    $('#temp-package-box').html('')
                    if(Id) {
                        console.log("重复数据")
                        $.get('/admin/gameChannel/getByIds', {ids: channelIds}, function (res) {
                            var channels = res.data;
                            var packages = []
                            channels.forEach(channel => {
                                channel.packages.forEach(x => {
                                    packages.push(x)
                                })
                            })
                            _this.packages = packages;
                            var html = laytpl($('#tempCheckboxList').prop("innerHTML")).render({
                                tempPackages: packages,
                                checkedIds: _this.packageCheckedIds, //默认选中
                            })
                            $('#temp-package-box').html(html)
                            form.render();

                        })
                    } else {
                        $.get('/admin/gameChannel/getByIdsHv',{ids:channelIds},function(res){
                            var channels = res.data;
                            var packages = []
                            channels.forEach(channel=>{
                                channel.packages.forEach(x=>{
                                    packages.push(x)
                                })
                            })
                            _this.packages = packages;
                            var html = laytpl($('#tempCheckboxList').prop("innerHTML")).render({
                                tempPackages: packages,
                                checkedIds: _this.packageCheckedIds, //默认选中
                            })
                            $('#temp-package-box').html(html)
                            form.render();

                        })}
                }

                form.on('checkbox(channel)',function(data){
                    var channelIds = _this.getValuesFromForm("channelId");

                    showPackagesByChannelIds(channelIds);
                })

                //监听提交
                form.on('submit(submit)', function (data) {

                    console.log('奖品列表',_this.rewardlist)
                    var formData = {
                        ...data.field,
                        rewardlist: JSON.stringify(_this.rewardlist.map(item => ({ id: parseInt(item.id), num: parseInt(item.num) })))
                    };
                    var channelIds = _this.getValuesFromForm('channelId[');
                    var packageIds = _this.getValuesFromForm('packageId[');
                    formData.channelIds = channelIds;
                    formData.packageIds = packageIds;
                    var pno=_this.packages;
                    let selectedPackages = [];
                    for (let i = 0; i < pno.length; i++) {
                        if (packageIds.includes(pno[i].id)) {
                            selectedPackages.push({
                                package_name:pno[i].id+":"+ pno[i].package_no,
                                packagenos:pno[i].package_no
                            });
                        }
                    }
                    console.log(packageIds.length)
                    if(packageIds.length<1){
                        console.log(!packageIds)
                        layer.msg("必须选择包",{icon:5})
                    }


                    formData.packages=selectedPackages;
                    if (Id){ //eidt
                        formData._method = 'put';
                        var willDeleteChannels = [];
                        initChannels.forEach(x=>{
                            if ( channelIds.indexOf(x.id) === -1 ) {
                                willDeleteChannels.push(x)
                            }
                        })
                        function postIt(){

                            $.post('/admin/gameSign/'+Id,formData,function(res){
                                if (res.code===0){
                                    layer.msg('success',{icon:6,time:500},function(){
                                        parent.location.reload();//父页面刷新
                                    })
                                } else {
                                    console.log('查看错误'+res.msg)
                                    layer.msg(res.msg,{icon:5})

                                }
                            })
                        }

                        if (willDeleteChannels.length > 0 ) {

                            var text = '';
                            willDeleteChannels.forEach(x=>{
                                text += `,${x.id}-${x.name}`
                            })
                            text = text.substring(1);
                            layer.confirm(`此次编辑删除了该分组下的 ${text} ，请确认`,{icon:3,title:"提示"},function(){
                                postIt();
                            })
                        } else {
                            postIt();
                        }

                    } else { //add

                        $.post('/admin/gameSign/add',formData,function(res){
                            if (res.code===0){

                                layer.msg('success',{icon:6,time:500},function(){
                                    parent.location.reload();//父页面刷新
                                })
                            } else {

                                layer.msg(res.msg,{icon:5})
                            }
                        })
                    }

                    return false;
                });

            });

        }
    })
</script>

</body>
</html>